package com.ekuaitu.kuaitustaff.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.bumptech.glide.Glide;
import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.adapter.CarsPagerAdapter;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.GetAppConfig;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.baiduMap.BaiduMapParams;
import com.ekuaitu.kuaitustaff.baiduMap.GeoCoderUtils;
import com.ekuaitu.kuaitustaff.baiduMap.LocationFilter;
import com.ekuaitu.kuaitustaff.baiduMap.MapStatusUtils;
import com.ekuaitu.kuaitustaff.baiduMap.MarkerUtils;
import com.ekuaitu.kuaitustaff.baiduMap.RoutePlan;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.CancelOrderBean;
import com.ekuaitu.kuaitustaff.bean.CarCheckUserIsPreOrderBean;
import com.ekuaitu.kuaitustaff.bean.CarCheckoutTaskBean;
import com.ekuaitu.kuaitustaff.bean.CarOrderBean;
import com.ekuaitu.kuaitustaff.bean.CarQueryStationBean;
import com.ekuaitu.kuaitustaff.bean.CarQuerylicenseBean;
import com.ekuaitu.kuaitustaff.bean.CarTaskDetailBean;
import com.ekuaitu.kuaitustaff.bean.CarTaskStateBean;
import com.ekuaitu.kuaitustaff.bean.CarTrackBean;
import com.ekuaitu.kuaitustaff.bean.CarUnfinishOrderCountBean;
import com.ekuaitu.kuaitustaff.bean.CompleteBean;
import com.ekuaitu.kuaitustaff.bean.DestinationBean;
import com.ekuaitu.kuaitustaff.bean.ForegroundBean;
import com.ekuaitu.kuaitustaff.bean.InitAppBean;
import com.ekuaitu.kuaitustaff.bean.ResultBean;
import com.ekuaitu.kuaitustaff.bean.ReturnCarCommentBean;
import com.ekuaitu.kuaitustaff.bean.SpecialOrderBean;
import com.ekuaitu.kuaitustaff.bean.StaffOrderBean;
import com.ekuaitu.kuaitustaff.bean.UserInforBean;
import com.ekuaitu.kuaitustaff.bean.lastUserLocation;
import com.ekuaitu.kuaitustaff.utils.AntiShake;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.CheckRegexUtils;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.DensityUtils;
import com.ekuaitu.kuaitustaff.utils.Dialogs.ChooseNaviDialog;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogCommentButton;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogOneButton;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogOrderDetail;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogTwoButton;
import com.ekuaitu.kuaitustaff.utils.IntentKey;
import com.ekuaitu.kuaitustaff.utils.IntentUtil;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.NetUtils;
import com.ekuaitu.kuaitustaff.utils.SDCardUtils;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.TimeUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.ble.BleConstants;
import com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper;
import com.ekuaitu.kuaitustaff.widget.CountDownIndicate;
import com.ekuaitu.kuaitustaff.widget.LoopViewPager;
import com.google.gson.Gson;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.baidu.location.BDLocation.TypeNetWorkLocation;
import static com.baidu.location.BDLocation.TypeServerError;
import static com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper.REQUEST_OPEN_BLE_ONCE;

public class CarNewMainMapActivity extends BaseActivity implements SensorEventListener {

    private Context mContext = this;
    private MapView mapView;
    private BaiduMap mBaiduMap;
    public LocationClient mLocClient;
    private static final int PERMISSION_REQUEST_CODE = 1;
    private SensorManager mSensorManager;
    private MyLocationData locData;
    private float mCurrentAccuracy;
    private Double lastX = 0.0;
    private MapStatusUtils mapStatusUtils;
    public static LatLng curPosition;
    private boolean isFirstLocationError = true;
    private MyLocationListener myListener = new MyLocationListener();
    private Boolean isFirstLocation = true;
    private MarkerUtils markerUtils;
    private String businessType = "1";
    private boolean isExit = false;
    private boolean isAnimatorShow = false;
    private RelativeLayout layout_car_detail, layout_car_driving;
    private ImageView iv_getorder, imageView_locate, iv_car, imageView_refresh;
    private TextView tx_reserve_order_timer, cancel_task, findCarFee, useCar, tv_username, tv_userphone, tv_blueState;
    private CountDownIndicate countDownIndicate;
    private LinearLayout layout_car_find, layout_car_receivedorder, linear_cancel, layout_search, linear_two;
    private CountDownTimer timer;//寻车倒计时
    private PowerManager.WakeLock wakeLock;
    private int showType = 0; //0默认页面 1展示类型 2寻车 3 任务进行中
    private String orderId, carId, licenseTag;
    private TextView tv_cancel, tv_inUse_license, tv_order_license, tv_received, tv_jifen;
    private ImageView driving_car_close, driving_car_open, driving_car_find, driving_car_return, iv_search, imageView_center;
    private RelativeLayout rl_timer;
    private ImageButton car_find, car_xiayibu;

    private List<CarOrderBean.AttachmentBean> carsResultList;//工单集合
    private List<CarQueryStationBean.AttachmentBean.StationListBean> stationResultList;//加油站充电桩集合
    private CarOrderBean.AttachmentBean attachmentBean;//选单
    private List<CarOrderBean.AttachmentBean> oneKeyAttachmentBean;//一键接单
    private CarOrderBean.AttachmentBean queryLicensesAttachmentBean;//搜车牌
    private List<CarOrderBean.AttachmentBean> listCarOrder;
    private List<CarTrackBean.AttachmentBean> carTracksList;//鹰眼轨迹
    private StaffOrderBean.AttachmentBean.ActionBean actionBean;//0:调度 1:充电 2:什么都不做 不可运营时不匹配终点 3：加油
    private String carStatus, taskType;
    private EditText edt_search;
    private LatLng foundCarPosition;
    private Bundle markerInfoBundle;
    private int markerindex;
    private Intent intent;
    private RelativeLayout rel_received;

    private BleConstants.OperateType operateType;
    private DrawerLayout drawer;
    private RelativeLayout main_content;
    private String userName, userPhone;
    private Button btn_change;
    private LinearLayout linear_jifen;
    private DialogOneButton unFinishTravelDialog;
    private TextView tvLastRank, tvRank, tvLastScore, tvScore;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable, 5000);
            checkUserIsPreOrderCar();
        }
    };
    private Call callParse;//之前外部有parse，虽然compositeDisposable.clear()了，但是parse是异步的响应，又走了一遍获取还车备注callParse.cancel会回调onFailure,所以判断!call.isCanceled()，再回调success!
    private RelativeLayout rl_findCarVip;
    private LatLng lastUserPhoneLocation;
    private boolean isClickxiayibu;
    private LoopViewPager vpCar;
    private CarsPagerAdapter carsPagerAdapter;
    private float layoutHeight;
    private int orderIndex = 0;
    private NetWorkStateReceiver netWorkStateReceiver;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        useCar = (TextView) findViewById(R.id.use_car);
        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_userphone = (TextView) findViewById(R.id.tv_userphone);
        findCarFee = (TextView) findViewById(R.id.find_car_fee_tip);
        btn_change = (Button) findViewById(R.id.btn_change);
        if (BuildConfig.DEBUG) {
            btn_change.setVisibility(View.VISIBLE);
        } else {
            btn_change.setVisibility(View.GONE);
        }
        tvLastRank = findViewById(R.id.personal_tv_rank0);
        tvRank = findViewById(R.id.personal_tv_rank1);
        tvLastScore = findViewById(R.id.personal_tv_score0);
        tvScore = findViewById(R.id.personal_tv_score1);
        rl_findCarVip = findViewById(R.id.rl_findCar);

        imageView_locate = (ImageView) findViewById(R.id.imageView_locate);
        imageView_center = (ImageView) findViewById(R.id.imageView_center);
        imageView_refresh = (ImageView) findViewById(R.id.imageView_refresh);

        linear_two = (LinearLayout) findViewById(R.id.linear_two);
        main_content = (RelativeLayout) findViewById(R.id.main_content);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        unFinishTravelDialog = new DialogOneButton(mContext);

        initAccessToken();
        initSearchLayout();
        initReceivedLayout();
        initDetailLayout();
        initFindLayout();
        initDrivingLayout();

        initMap();
        getPermission();
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
    }

    public class NetWorkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("网络状态发生变化");
            if (NetUtils.isNetworkAvailable(mContext) && (showType == 0 || showType == 1)) {
                layout_search.setVisibility(View.VISIBLE);
            } else {
                layout_search.setVisibility(View.INVISIBLE);
            }
        }
    }

    //搜索布局
    private void initSearchLayout() {
        layout_search = (LinearLayout) findViewById(R.id.layout_search);
        linear_cancel = (LinearLayout) findViewById(R.id.linear_cancel);

        edt_search = (EditText) findViewById(R.id.edt_search);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);

        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!edt_search.getText().toString().equals(CheckRegexUtils.carNumFilter(edt_search.getText().toString()))) {
                    edt_search.setText(CheckRegexUtils.carNumFilter(edt_search.getText().toString()));
                    edt_search.setSelection(CheckRegexUtils.carNumFilter(edt_search.getText().toString()).length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && linear_cancel.getVisibility() == View.GONE) {
                    linear_cancel.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    linear_cancel.setVisibility(View.GONE);
                }
            }
        });
        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (TextUtils.isEmpty(edt_search.getText().toString())) {
                        ToastUtils.makeText(mContext, "请输入要查询的车牌号", ToastUtils.LENGTH_SHORT).show();
                    } else {
                        if (CheckRegexUtils.isCarNum(edt_search.getText().toString())) {
                            queryLicense(edt_search.getText().toString());
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, "请输入正确的车牌号", ToastUtils.LENGTH_SHORT).show();
                        }
                    }
                }
                return false;
            }
        });
    }

    //已接工单布局
    private void initReceivedLayout() {
        layout_car_receivedorder = (LinearLayout) findViewById(R.id.layout_car_receivedorder);
        tv_received = (TextView) findViewById(R.id.tv_received);
        rel_received = (RelativeLayout) findViewById(R.id.rel_received);

    }

    //接单弹窗
    private void initDetailLayout() {
        layout_car_detail = (RelativeLayout) findViewById(R.id.layout_car_detail);
        iv_getorder = (ImageView) findViewById(R.id.iv_getorder);
        vpCar = (LoopViewPager) findViewById(R.id.vp_car);
        vpCar.addOnPageChangeListener(new LoopViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (callParse != null) {
                    callParse.cancel();
                }
                compositeDisposable.clear();
                mBaiduMap.hideInfoWindow();
                orderIndex = position + 1;
                Logger.d("pagerPosition", position + "  pagerPositionOut");
                attachmentBean = listCarOrder.get(position);
                orderId = attachmentBean.getOrderId();
                carId = attachmentBean.getCarId();
                taskType = attachmentBean.getTaskType();
                licenseTag = attachmentBean.getLicenseTag();
                foundCarPosition = new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude());
                mapStatusUtils.animateMove(foundCarPosition, 17, 300, (int) layoutHeight - 120);
                //获取还车备注
                getReturnComment(attachmentBean.getDistributeReason(), attachmentBean.getIsAccurate(), attachmentBean.getCarId(), attachmentBean.getRemark(), 1, foundCarPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    //初始化下单寻车弹出布局
    private void initFindLayout() {

        layout_car_find = (LinearLayout) findViewById(R.id.layout_car_find);
        rl_timer = (RelativeLayout) findViewById(R.id.rl_timer);
        iv_car = (ImageView) findViewById(R.id.iv_car);
        cancel_task = (TextView) findViewById(R.id.cancel_task);
        tv_order_license = (TextView) findViewById(R.id.tv_order_license);
        tx_reserve_order_timer = (TextView) findViewById(R.id.tx_place_order_timer);
        car_find = (ImageButton) findViewById(R.id.car_find);
        car_xiayibu = (ImageButton) findViewById(R.id.car_xiayibu);
        countDownIndicate = (CountDownIndicate) findViewById(R.id.cd_indicate);

        car_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!NetUtils.isNetworkAvailable(mContext)) {
                    ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                } else {
                    if ("2".equals(carStatus) || "3".equals(carStatus)) {
                        showOneButtonDialog("checkCarStatus", "有用户预订", "请等待用户预订结果", "知道了");
                    } else {
                        controlCar("beep", "寻车中鸣笛", "寻车中鸣笛");
                    }
                }

            }
        });
        car_xiayibu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isClickxiayibu = true;
                if (!NetUtils.isNetworkAvailable(mContext)) {
                    ToastUtils.makeText(mContext, getString(R.string.goTohaveNet), ToastUtils.LENGTH_SHORT).show();
                } else {
                    if ("2".equals(carStatus) || "3".equals(carStatus)) {
                        showOneButtonDialog("checkCarStatus", "有用户预订", "请等待用户预订结果", "知道了");
                    } else {
                        if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                            showLoadingDialog();
                            //蓝牙开，未连接
                            if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                                BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
                                Logger.i("bleinfo_xiayibu", "蓝牙开，未连接");
                            }
                            //蓝牙开，已连接
                            else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                                openRecord(orderId, "1");
                                Logger.i("bleinfo_xiayibu", "蓝牙开，连接");
                            }
                            //蓝牙未开
                            else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                                BluetoothHelper.getInstance().openBluetooth(CarNewMainMapActivity.this, REQUEST_OPEN_BLE_ONCE);
                                Logger.i("bleinfo_xiayibu", "蓝牙未开");
                            }
                        } else {
                            openRecord(orderId, "2");
                            BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);
                        }
                    }
                }
            }
        });
        cancel_task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCancelTask();
            }
        });
    }

    //开门检查之后 行驶中
    private void initDrivingLayout() {

        layout_car_driving = (RelativeLayout) findViewById(R.id.layout_car_driving);
        driving_car_close = (ImageView) findViewById(R.id.driving_car_close);
        driving_car_open = (ImageView) findViewById(R.id.driving_car_open);
        driving_car_find = (ImageView) findViewById(R.id.driving_car_find);
        driving_car_return = (ImageView) findViewById(R.id.driving_car_return);
        tv_inUse_license = (TextView) findViewById(R.id.tv_inUse_license);
        tv_blueState = (TextView) findViewById(R.id.tv_blueState);
        linear_jifen = (LinearLayout) findViewById(R.id.linear_jifen);
        tv_jifen = (TextView) findViewById(R.id.tv_jifen);

        driving_car_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!NetUtils.isNetworkAvailable(mContext)) {
                    ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                } else {
                    controlCar("beep", "行驶中鸣笛", "行驶中鸣笛");
                }
            }
        });
        driving_car_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                operateType = BleConstants.OperateType.OPEN_DOOR_POWER;
                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                    showLoadingDialog();
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        controlCar("open", "行驶中开门", "行驶中开门");
                        BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        BluetoothHelper.getInstance().operateCar(true, "开门加电", operateType, onOperateCarListener);
                    }
                    //蓝牙未开
                    else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                        BluetoothHelper.getInstance().openBluetooth(CarNewMainMapActivity.this, REQUEST_OPEN_BLE_ONCE);
                    }
                } else {
                    BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);
                    controlCar("open", "行驶中开门", "行驶中开门");
                }
            }
        });

        driving_car_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                operateType = BleConstants.OperateType.CLOSE_DOOR_POWER;
                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                    showLoadingDialog();
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        controlCar("close", "行驶中关门", "行驶中关门");
                        BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        BluetoothHelper.getInstance().operateCar(true, "关门断电", operateType, onOperateCarListener);
                    }
                    //蓝牙未开
                    else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                        BluetoothHelper.getInstance().openBluetooth(CarNewMainMapActivity.this, REQUEST_OPEN_BLE_ONCE);
                    }
                } else {
                    controlCar("close", "行驶中关门", "行驶中关门");
                    BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);
                }
            }
        });

        driving_car_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    checkoutTask(orderId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        findCarFee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtil.toCarParkingFeeActivity(mContext, orderId, carId, licenseTag);
            }
        });
    }

    //初始化OCR单利
    private void initAccessToken() {
        OCR.getInstance(mContext).initAccessToken(new com.baidu.ocr.sdk.OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Logger.i("OCRTOKEN", error.getMessage());
            }
        }, mContext);
    }

    //初始化地图
    public void initMap() {
        mapView = (MapView) findViewById(R.id.map_mainActivity);
        mapView.showZoomControls(false);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        if (mBaiduMap == null) {
            mBaiduMap = mapView.getMap();
            // 开启定位图层
            mBaiduMap.setBuildingsEnabled(false);
            mBaiduMap.setMyLocationEnabled(true);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true,
                    BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation), 0x00000000, 0x00000000));
            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);
            // 定位初始化
            mLocClient = new LocationClient(this);
            LocationClientOption option = new LocationClientOption();
            option.setIsNeedAddress(true);
            option.setIsNeedLocationDescribe(true);
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(8000);
            mLocClient.setLocOption(option);
            mLocClient.registerLocationListener(myListener);

            markerUtils = new MarkerUtils(mBaiduMap, mContext);
            mapStatusUtils = new MapStatusUtils(mBaiduMap, mContext);
            //mapStatusUtils.defaultPosition();
            mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    if (callParse != null) {
                        callParse.cancel();
                    }
                    compositeDisposable.clear();
                    backPress(false);
                }

                @Override
                public boolean onMapPoiClick(MapPoi mapPoi) {
                    return false;
                }
            });
            mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override//0:调度 1:充电 2:什么都不做 不可运营时不匹配终点 3：加油
                public boolean onMarkerClick(final Marker marker) {
                    try {
                        if (callParse != null) {
                            callParse.cancel();
                        }
                        compositeDisposable.clear();
                        mBaiduMap.hideInfoWindow();
                        markerInfoBundle = marker.getExtraInfo();

                        if ((showType == 0 || showType == 1) && markerInfoBundle != null) {
                            if (MarkerUtils.MarkerType.CAR.name().equals(markerInfoBundle.getString("markerType")) && carsResultList != null && !carsResultList.isEmpty()) {
                                attachmentBean = carsResultList.get(markerInfoBundle.getInt("carMarkerId"));
                                listCarOrder = new ArrayList<>();
                                listCarOrder.add(attachmentBean);
                                loadOrderDetailLayout(listCarOrder, "4");
                            } else if (MarkerUtils.MarkerType.QUERY_LICENSE.name().equals(markerInfoBundle.getString("markerType"))) {
                                if (queryLicensesAttachmentBean != null) {
                                    listCarOrder = new ArrayList<>();
                                    listCarOrder.add(queryLicensesAttachmentBean);
                                    loadOrderDetailLayout(listCarOrder, "4");
                                }
                            } else if (MarkerUtils.MarkerType.ONEKEYRECEIVE_CAR.name().equals(markerInfoBundle.getString("markerType"))) {
                                if (oneKeyAttachmentBean != null) {
                                    listCarOrder = new ArrayList<>();
                                    listCarOrder.add(oneKeyAttachmentBean.get(markerInfoBundle.getInt("carMarkerId")));
                                    loadOrderDetailLayout(listCarOrder, "4");
                                }
                            }
                        } else if (showType == 2 && markerInfoBundle != null) {
                            if (MarkerUtils.MarkerType.LAST_USER_PHONE.name().equals(markerInfoBundle.getString("markerType"))) {
                                markerUtils.showLastUserPhoneInfoWindow("", lastUserPhoneLocation, new MarkerUtils.NaviButtonClickListener() {
                                    @Override
                                    public void onClick() {
                                        showNaviDialog(lastUserPhoneLocation);
                                    }
                                });
                            } else if (MarkerUtils.MarkerType.END_POSITION_MARKER.name().equals(markerInfoBundle.getString("markerType"))) {
                                getReturnComment(attachmentBean.getDistributeReason(), attachmentBean.getIsAccurate(), attachmentBean.getCarId(), attachmentBean.getRemark(), 2, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()));
                            }
                        } else if (showType == 3 && markerInfoBundle != null) {
                            if ((MarkerUtils.MarkerType.CAR.name().equals(markerInfoBundle.getString("markerType"))) && carsResultList != null && !carsResultList.isEmpty()) {
                                attachmentBean = carsResultList.get(markerInfoBundle.getInt("carMarkerId"));
                                getReturnComment(attachmentBean.getDistributeReason(), attachmentBean.getIsAccurate(), attachmentBean.getCarId(), attachmentBean.getRemark(), 1, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()));
                                showDialogReceiveMore(attachmentBean);
                            } else if ((MarkerUtils.MarkerType.STATION_POSITION_MARKER.name().equals(markerInfoBundle.getString("markerType"))) && stationResultList != null && !stationResultList.isEmpty()) {
                                markerindex = markerInfoBundle.getInt("carMarkerId");
                                markerUtils.showFindCarInfoWindow(stationResultList.get(markerindex).getStationName(), new LatLng(stationResultList.get(markerindex).getLatitude(), stationResultList.get(markerindex).getLongitude()), new MarkerUtils.NaviButtonClickListener() {
                                    @Override
                                    public void onClick() {
                                        showNaviDialog(new LatLng(stationResultList.get(markerindex).getLatitude(), stationResultList.get(markerindex).getLongitude()));
                                    }
                                });
                                RoutePlan.getInstance().clearDrvingRoutePlanning();
                                RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, curPosition, new LatLng(stationResultList.get(markerindex).getLatitude(), stationResultList.get(markerindex).getLongitude()), null);
                                if (actionBean != null && ("1").equals(actionBean.getActionType())) {//充电
                                    searchCarOrderByRange(stationResultList.get(markerindex).getLatitude() + "", stationResultList.get(markerindex).getLongitude() + "", orderId, "");
                                }
                            } else if ((MarkerUtils.MarkerType.END_POSITION_MARKER.name().equals(markerInfoBundle.getString("markerType")))) {
                                markerUtils.showFindCarInfoWindow(actionBean.getLocation(), new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), new MarkerUtils.NaviButtonClickListener() {
                                    @Override
                                    public void onClick() {
                                        showNaviDialog(new LatLng(actionBean.getLatitude(), actionBean.getLongitude()));
                                    }
                                });
                                if (actionBean != null && ("3").equals(actionBean.getActionType())) {
                                    RoutePlan.getInstance().clearDrvingRoutePlanning();
                                    RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, curPosition, new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), null);
                                }

                            } else if ((MarkerUtils.MarkerType.WASH_CAR.name().equals(markerInfoBundle.getString("markerType")))) {
                                markerUtils.showFindCarInfoWindow(actionBean.getWashLocationName(), new LatLng(actionBean.getWashLatitude(), actionBean.getWashLongitude()), new MarkerUtils.NaviButtonClickListener() {
                                    @Override
                                    public void onClick() {
                                        showNaviDialog(new LatLng(actionBean.getWashLatitude(), actionBean.getWashLongitude()));
                                    }
                                });
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            });

        }
    }

    @OnClick({R.id.imageView_center, R.id.imageView_locate, R.id.use_car, R.id.rl_orderlist, R.id.iv_search, R.id.tv_cancel, R.id.rel_received, R.id.cancel_task, R.id.rl_service, R.id.rl_setting, R.id.imageView_refresh, R.id.btn_change, R.id.rl_carscan, R.id.rl_findCar, R.id.main_comment})
    public void onViewClicked(View view) {
        if (AntiShake.check(view.getId())) return; //判断是否多次点击
        switch (view.getId()) {
            case R.id.imageView_center:
                getUserInfor();
                break;
            case R.id.imageView_locate:
                if (curPosition != null) {
                    if (showType == 2 || showType == 1) {
                        mapStatusUtils.animateMove(curPosition, 16, 600);
                    } else {
                        mapStatusUtils.animateMove(curPosition, 16, 600, 0);
                    }
                } else {
                    ToastUtils.makeText(mContext, "正在定位...", ToastUtils.LENGTH_SHORT).show();
                }

                break;
            case R.id.imageView_refresh:

                getCarList();
                if (showType == 1) {
                    popCarLayout(layout_car_detail, false, null);
                }

                break;
            case R.id.use_car:
                if (curPosition != null && curPosition.latitude != 0 && curPosition.longitude != 0) {
                    //一键选车
                    oneKeyReciveOrder();
                }
                break;
            case R.id.rl_orderlist:
                IntentUtil.toWebViewActivity(mContext, UrlConstant.Request.WORKLIST);
                break;
            case R.id.rl_service:
                IntentUtil.toWebViewActivity(mContext, UrlConstant.Request.HOTLINE);
                break;
            case R.id.rl_setting:
                IntentUtil.toWebViewActivity(mContext, UrlConstant.Request.SETTING);
                break;
            case R.id.rl_carscan:
                IntentUtil.toCarScanActivity(mContext);
                break;
            case R.id.rl_findCar:
                IntentUtil.toFindCarActivity(mContext);
                break;
            case R.id.main_comment:
                IntentUtil.toAddCommentActivity(mContext);
                break;
            case R.id.iv_search:
                if (TextUtils.isEmpty(edt_search.getText().toString())) {
                    ToastUtils.makeText(mContext, "请输入要查询的车牌号", ToastUtils.LENGTH_SHORT).show();
                } else {
                    if (CheckRegexUtils.isCarNum(edt_search.getText().toString())) {
                        queryLicense(edt_search.getText().toString());
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, "请输入正确的车牌号", ToastUtils.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.tv_cancel:
                edt_search.setText("");
                linear_cancel.setVisibility(View.GONE);
                break;
            case R.id.rel_received:
                intent = new Intent(mContext, CarReceiveRecordActivity.class);
                startActivityForResult(intent, Constants.REQUEST_CAR_RECEIVEDLIST);
                break;
            case R.id.cancel_task:
                showCancelTask();
                break;
            case R.id.btn_change:
                intent = new Intent(mContext, DebugModeActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            int mCurrentDirection = (int) x;
            if (curPosition != null) {
                locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccuracy)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mCurrentDirection).latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();
                mBaiduMap.setMyLocationData(locData);
            }
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mapView == null) {
                showOneButtonDialog("locationException", "提醒", "定位异常，请退出应用再试。", "确定");
                return;
            }
            int locationErrorCode = bdLocation.getLocType();
            if (locationErrorCode == BDLocation.TypeGpsLocation || locationErrorCode == TypeNetWorkLocation) {

                //GPS或者网络定位成功
                Logger.i("curPositionMain", "纬度" + bdLocation.getLatitude() + "经度" + bdLocation.getLongitude()
                        + "citycode" + bdLocation.getCityCode() + "countrycode" + bdLocation.getCountryCode());
                bdLocation = LocationFilter.Algorithm(bdLocation);//根据历史定位，对定位的结果平滑过滤

                if (!BuildConfig.DEBUG) {
                    curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                    ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                    ((MyApplication) getApplication()).setAdCode(bdLocation.getAdCode());
                    ((MyApplication) getApplication()).setCurPosition(curPosition.latitude + "", curPosition.longitude + "");
                } else {
                    switch (SPUtils.getInstance(mContext).getIntValue(SPKey.LOCATIONMOED)) {
                        case 0:
                        case 1:
                            curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位

                            ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                            ((MyApplication) getApplication()).setAdCode(bdLocation.getAdCode());
                            ((MyApplication) getApplication()).setCurPosition(curPosition.latitude + "", curPosition.longitude + "");
                            break;
                        case 2:
                            curPosition = new LatLng(Double.parseDouble(SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LATITUDE)),
                                    Double.parseDouble(SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LONGITUDE)));// 更新定位
                            Logger.i(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                            ((MyApplication) getApplication()).setAreaCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                            ((MyApplication) getApplication()).setAdCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE));
                            ((MyApplication) getApplication()).setCurPosition(SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LATITUDE),
                                    SPUtils.getInstance(mContext).getStringValue(SPKey.FIX_LONGITUDE));
                            Logger.i(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE) + "省市");
                            break;
                    }

                }

                mCurrentAccuracy = bdLocation.getRadius();
                locData = new MyLocationData.Builder()
                        .accuracy(mCurrentAccuracy)
                        .direction(bdLocation.getDirection())// 此处设置开发者获取到的方向信息，顺时针0-360
                        .latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();

                mBaiduMap.setMyLocationData(locData);
                if (isFirstLocation) {//首次成功的定位
                    isFirstLocation = false;
                    initLocationService();
                    mapStatusUtils.animateMove(curPosition, 16, 400, 0);
                    GetAppConfig.getInstance(mContext).getConfig(() -> {
                        initApp();
                    });
                }
                //寻车距离
                if (foundCarPosition != null) {
                    Logger.i("distance", DistanceUtil.getDistance(curPosition, foundCarPosition) + "=====" + SPUtils.getInstance(mContext).getIntValue(SPKey.FIND_CAR_DISTANCE));
                    if (DistanceUtil.getDistance(curPosition, foundCarPosition)
                            <= SPUtils.getInstance(mContext).getIntValue(SPKey.FIND_CAR_DISTANCE)) {
                        car_find.setVisibility(View.VISIBLE);

                    } else {
                        car_find.setVisibility(View.INVISIBLE);
                    }
                }
            } else {//定位失败
                Logger.i("loctionerror", bdLocation.getLocType() + "");
                if (isFirstLocationError && isFirstLocation) {  //第一次定位失败执行，之后的失败定位不再执行
                    isFirstLocationError = false;
                    if (locationErrorCode == TypeServerError) {  //缺少定位权限
                        showOneButtonDialog("permission", "提醒", "您可能拒绝了定位权限，请在设置中开启权限。", "去设置");
                    } else {
                        showOneButtonDialog("locationfail", "提醒", "定位失败，请检查定位服务是否开启，网络是否正常。", "去设置");
                    }
                }
            }
        }

    }

    //获取初始化信息
    private void initApp() {
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM) == null) {
            startActivity(new Intent(mContext, LoginNewActivity.class));
            return;
        }
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).initApp(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<InitAppBean>() {
                    @Override
                    public void onResponse(Call<InitAppBean> call, Response<InitAppBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                Logger.i("parse", "retrofitRes" + "初始化接口成功" + response.body().getErrCode());
                                MyApplication.imageUrl = response.body().getAttachment().getImgUrl();
                                MyApplication.hotLine = response.body().getAttachment().getService_call();
                                SPUtils.getInstance(mContext).putStringValue(SPKey.HOT_LINE, MyApplication.hotLine);
                                SPUtils.getInstance(mContext).putIntValue(SPKey.FIND_CAR_DISTANCE, response.body().getAttachment().getDistanceJudgment());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.AREA_CODE, MyApplication.getInstance().getAreaCode());

                                getunfinishOrder();//检查是否有进行中状态

                            } else if (response.body().getErrCode() == 11) {
                                intent = new Intent(mContext, LoginNewActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();

                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<InitAppBean> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //是否有进行中的工单
    private void getunfinishOrder() {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).unfinishOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CarTaskStateBean>() {
                    @Override
                    public void onResponse(Call<CarTaskStateBean> call, Response<CarTaskStateBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                Logger.i("parse", "retrofitRes" + "未完成工单接口成功");
                                if ("1".equals(response.body().getAttachment().getHasOrderOrNot())) {
                                    getCarList();
                                } else {
                                    if (response.body().getAttachment().getStaffCarOrderModel() != null) {
                                        attachmentBean = response.body().getAttachment().getStaffCarOrderModel();
                                        actionBean = response.body().getAttachment().getAction();

                                        orderId = attachmentBean.getOrderId();
                                        carId = attachmentBean.getCarId();
                                        taskType = attachmentBean.getTaskType();
                                        foundCarPosition = new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude());

                                        showUnFinishDialog(attachmentBean);
                                    }
                                }
                            } else if (response.body().getErrCode() == 11) {
                                intent = new Intent(mContext, LoginNewActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarTaskStateBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "未完成接口" + t.toString());
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //获取电车工单
    private void getCarList() {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getCarOrder(MyApplication.getInstance().getRequestFieldMap(), businessType, "1", "100")
                .enqueue(new Callback<CarOrderBean>() {
                    @Override
                    public void onResponse(Call<CarOrderBean> call, final Response<CarOrderBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                carsResultList = response.body().getAttachment();
                                //添加接单标记
                                if (carsResultList.size() != 0) {
                                    mBaiduMap.clear();
                                    markerUtils.addCarMarkersToMap(carsResultList);
                                }
                                getSpecialOrderList();
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                dismissLoadingDialog();
                                mBaiduMap.clear();
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarOrderBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "工单列表" + t.toString());
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    public void getSpecialOrderList() {
        if (TextUtils.isEmpty(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE))) {
            return;
        }
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getSpecialOrders(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<SpecialOrderBean>() {
            @Override
            public void onResponse(Call<SpecialOrderBean> call, Response<SpecialOrderBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0) {
                        //添加送车上门marker
                        if (response.body().getAttachment() != null && response.body().getAttachment().size() > 0) {
                            markerUtils.addSpecialMarkerToMap(response.body().getAttachment());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<SpecialOrderBean> call, Throwable t) {

            }
        });
    }

    //个人中心
    private void getUserInfor() {
        showLoadingDialog();
        if (MyApplication.findCarVip != null && MyApplication.findCarVip.contains(MyApplication.getInstance().getUserId())) {
            rl_findCarVip.setVisibility(View.VISIBLE);
        }
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).userInfo(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<UserInforBean>() {
                    @Override
                    public void onResponse(Call<UserInforBean> call, Response<UserInforBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                drawer.openDrawer(Gravity.START);
                                if (response.body().getAttachment() != null) {
                                    userName = response.body().getAttachment().getStaffUser().getName();
                                    userPhone = response.body().getAttachment().getStaffUser().getPhoneNum();
                                    tv_username.setText(userName);
                                    tv_userphone.setText(userPhone);
                                    tvLastRank.setText(response.body().getAttachment().getStaffUser().getLastMonthRank());
                                    tvRank.setText(response.body().getAttachment().getStaffUser().getCurrentRank());
                                    tvLastScore.setText(response.body().getAttachment().getStaffUser().getLastMonthScore());
                                    tvScore.setText(response.body().getAttachment().getStaffUser().getCurrentMonthScore());
                                }
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<UserInforBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "个人信息" + t.toString());
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //搜索
    private void queryLicense(final String license) {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).queryLicense(MyApplication.getInstance().getRequestFieldMap(), license)
                .enqueue(new Callback<CarQuerylicenseBean>() {
                    @Override
                    public void onResponse(Call<CarQuerylicenseBean> call, Response<CarQuerylicenseBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                if (response.body().getAttachment() != null) {
                                    queryLicensesAttachmentBean = response.body().getAttachment();
                                    markerUtils.removeOneMarker();
                                    markerUtils.addOneCarMarkerToMap(queryLicensesAttachmentBean, 2, 0);
                                    listCarOrder = new ArrayList<>();
                                    listCarOrder.add(queryLicensesAttachmentBean);
                                    loadOrderDetailLayout(listCarOrder, "2");
                                }
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else if (response.body().getErrCode() == 1001) {
                                showOneButtonDialog("nopermission", "提醒", response.body().getMessage(), "确定");
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarQuerylicenseBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "搜索车牌号" + t.toString());
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //确认接单 reciveType 1:一键接单.2:搜索.4:大头针
    private void receiveOrder(String orderId, String licenseTag, String reciveType, int orderIndex) {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "确认接单");
        eventMap.put("comment", "接单");
        eventMap.put("order", orderId);
        eventMap.put("car", licenseTag);
        eventMap.put("reciveType", reciveType);

        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "staff/staff/v/staff-order/receive", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.receiveOrder(MyApplication.getInstance().getRequestFieldMap(), orderId, businessType, reciveType, orderIndex)
                        .enqueue(new Callback<ResultBean>() {
                            @Override
                            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    dismissLoadingDialog();
                                    if (response.body().getErrCode() == 0) {
                                        //接单成功 0没开门
                                        isOpenCheck("0");
                                    } else if (response.body().getErrCode() == 11) {
                                        IntentUtil.toLoginActivity(mContext);
                                        AppManager.getAppManager().finishAllActivity();
                                    } else if (response.body().getErrCode() == 1001) {
                                        showOneButtonDialog("nopermission", "提醒", response.body().getMessage(), "确定");
                                    } else {
                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                                    }
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                dismissLoadingDialog();
                                Log.i("neterror", "确认接单" + t.toString());
                                ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }

    //一键接单
    private void oneKeyReciveOrder() {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).oneKeyReciveOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CarTaskDetailBean>() {
                    @Override
                    public void onResponse(Call<CarTaskDetailBean> call, Response<CarTaskDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                oneKeyAttachmentBean = response.body().getAttachment();
                                if (oneKeyAttachmentBean != null) {
                                    markerUtils.removeOneMarker();
                                    for (int i = 0; i < oneKeyAttachmentBean.size(); i++) {
                                        markerUtils.addOneCarMarkerToMap(oneKeyAttachmentBean.get(i), 1, i);
                                    }
                                    listCarOrder = new ArrayList<>();
                                    listCarOrder.addAll(oneKeyAttachmentBean);
                                    loadOrderDetailLayout(listCarOrder, "1");
                                }
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else if (response.body().getErrCode() == 1001) {
                                showOneButtonDialog("nopermission", "提醒", response.body().getMessage(), "确定");
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarTaskDetailBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "一键接单" + t.toString());
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //检测调度工单是否有人预约接口
    private void checkUserIsPreOrderCar() {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class)
                .checkUserIsPreOrderCar(MyApplication.getInstance().getRequestFieldMap(), carId, orderId)
                .enqueue(new Callback<CarCheckUserIsPreOrderBean>() {
                    @Override
                    public void onResponse(Call<CarCheckUserIsPreOrderBean> call, Response<CarCheckUserIsPreOrderBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getErrCode() == 0) {
                                if (response.body().getAttachment() != null) {
                                    //1无人预定，2：已有人约定；3：车辆被使用;4:停止轮询
                                    carStatus = response.body().getAttachment().getStatus();
                                    if ("2".equals(response.body().getAttachment().getStatus())) {
                                        if (timer != null) {
                                            timer.cancel();
                                            timer = null;
                                        }
                                        rl_timer.setVisibility(View.VISIBLE);
                                        findCarTimer(response.body().getAttachment().getExpireTime() * 1000);
                                    } else if ("1".equals(response.body().getAttachment().getStatus())) {
                                        if (timer != null) {
                                            timer.cancel();
                                            timer = null;
                                        }
                                        releaseWakeLock();
                                        rl_timer.setVisibility(View.GONE);
                                    } else if ("3".equals(response.body().getAttachment().getStatus())) {
                                        if (timer != null) {
                                            timer.cancel();
                                            timer = null;
                                        }
                                        releaseWakeLock();
                                        rl_timer.setVisibility(View.GONE);
                                        handler.removeCallbacks(runnable);
                                        cancelTaskAuto();
                                    } else if ("4".equals(response.body().getAttachment().getStatus())) {
                                        if (timer != null) {
                                            timer.cancel();
                                            timer = null;
                                        }
                                        releaseWakeLock();
                                        rl_timer.setVisibility(View.GONE);
                                        handler.removeCallbacks(runnable);
                                    }
                                }
                            } else if (response.body().getErrCode() == 11) {
                                if (timer != null) {
                                    timer.cancel();
                                    timer = null;
                                }
                                releaseWakeLock();
                                rl_timer.setVisibility(View.GONE);
                                handler.removeCallbacks(runnable);
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CarCheckUserIsPreOrderBean> call, Throwable t) {
                        Log.i("neterror", "是否有人预约" + t.toString());
                    }
                });
    }

    private void cancelTaskAuto() {
        final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
        dialogOneButton.setTitle("提醒");
        dialogOneButton.setMessage("车辆被用户使用，工单已取消");
        dialogOneButton.setCancelable(false);
        dialogOneButton.setCanceledOnTouchOutside(false);
        dialogOneButton.setYesOnclickListener("确定", new DialogOneButton.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                popCarLayout(layout_car_find, false, null);
                mBaiduMap.clear();
                getunfinishOrder();
                dialogOneButton.dismiss();
            }
        });
        dialogOneButton.show();

    }

    //已接工单列表个数
    private void getReceiveOrderListCount() {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getunfinishOrderCount(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CarUnfinishOrderCountBean>() {
                    @Override
                    public void onResponse(Call<CarUnfinishOrderCountBean> call, final Response<CarUnfinishOrderCountBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                tv_received.setText("有" + response.body().getAttachment().getCount() + "个待完成的工单");
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarUnfinishOrderCountBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "未完成个数接口" + t.toString());
                        ToastUtils.makeText(mContext, getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    //取消任务
    public void cancelTask(final String orderId) {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "取消任务");
        eventMap.put("comment", "取消任务");
        eventMap.put("order", orderId);
        eventMap.put("car", licenseTag);
        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/staff-order/cancelWorkOrder", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.cancelOrder(MyApplication.getInstance().getRequestFieldMap(),
                        businessType, orderId)
                        .enqueue(new Callback<CancelOrderBean>() {
                            @Override
                            public void onResponse(Call<CancelOrderBean> call, Response<CancelOrderBean> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    dismissLoadingDialog();
                                    if (response.body().getErrCode() == 0) {
                                        handler.removeCallbacks(runnable);
                                        ToastUtils.makeText(mContext, "工单已取消", 1, ToastUtils.LENGTH_SHORT).show();
                                        popCarLayout(layout_car_find, false, null);
                                        mBaiduMap.clear();
                                        getunfinishOrder();
                                    } else if (response.body().getErrCode() == 11) {
                                        IntentUtil.toLoginActivity(mContext);
                                        AppManager.getAppManager().finishAllActivity();
                                    } else {
                                        dismissLoadingDialog();
                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_LONG).show();
                                    }
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<CancelOrderBean> call, Throwable t) {
                                dismissLoadingDialog();
                                Log.i("neterror", "取消任务" + t.toString());
                                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_LONG).show();
                            }
                        });
            }
        });

    }

    //根据坐标提供附近2公里的工单
    public void searchCarOrderByRange(final String endLatitude, final String endLongitude, final String workOrderId, final String electricPileModels) {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).searchCarOrderByRange(MyApplication.getInstance().getRequestFieldMap(), businessType
                , endLatitude, endLongitude, workOrderId, electricPileModels)
                .enqueue(new Callback<CarOrderBean>() {
                    @Override
                    public void onResponse(Call<CarOrderBean> call, Response<CarOrderBean> response) {
                        dismissLoadingDialog();
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getErrCode() == 0) {
                                //附近两公里列表
                                if (response.body().getAttachment() != null) {
                                    carsResultList = response.body().getAttachment();
                                    //添加接单标记
                                    if (carsResultList.size() != 0) {
                                        markerUtils.removeParksAndCarsMarker();
                                        markerUtils.addCarMarkersToMap(carsResultList);
                                    }
                                }
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarOrderBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "附近工单" + t.toString());
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();

                    }
                });
    }

    //根据坐标查询充电桩或者加油站
    public void queryStation(final String latitudeCar, final String longitudeCar, final String type) {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).queryStation(MyApplication.getInstance().getRequestFieldMap(), latitudeCar, longitudeCar, type
        )
                .enqueue(new Callback<CarQueryStationBean>() {
                    @Override
                    public void onResponse(Call<CarQueryStationBean> call, Response<CarQueryStationBean> response) {
                        dismissLoadingDialog();
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getErrCode() == 0) {
                                if (response.body().getAttachment() != null) {
                                    stationResultList = response.body().getAttachment().getStationList();
                                    if (stationResultList.size() != 0) {
                                        markerUtils.addStationMarkersToMap(stationResultList, type);
                                    }
                                }
                            } else if (response.body().getErrCode() == 11) {
                                IntentUtil.toLoginActivity(mContext);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();

                            }
                        } else {
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CarQueryStationBean> call, Throwable t) {
                        dismissLoadingDialog();
                        Log.i("neterror", "充电桩或加油站" + t.toString());
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }


    //获取蓝牙信息
    private void getBleInfoAndSearch() {
        BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, new BluetoothHelper.OnGetBleResponse() {
            @Override
            public void getBleResponse() {
                operateType = null;
                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        showLoadingDialog();
                        Logger.i("bleinfo_onresume", "蓝牙开，未连接");
                        BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        Logger.i("bleinfo_onresume", "蓝牙开，连接");
                        tv_blueState.setText("蓝牙已匹配");
                    }
                    //蓝牙未开
                    else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                        BluetoothHelper.getInstance().openBluetooth(CarNewMainMapActivity.this, REQUEST_OPEN_BLE_ONCE);
                    }
                }
            }
        });

    }

    //鹰眼轨迹
    private void getDriveTracks() {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getCarTrack(MyApplication.getInstance().getRequestFieldMap(), carId).enqueue(new Callback<CarTrackBean>() {
            @Override
            public void onResponse(Call<CarTrackBean> call, Response<CarTrackBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        carTracksList = response.body().getAttachment();
                        //添加接单标记
                        if (carTracksList.size() != 0) {
                            markerUtils.addDriveTracksToMap(carTracksList);
                        }
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CarTrackBean> call, Throwable t) {
                dismissLoadingDialog();
                Log.i("neterror", "鹰眼轨迹" + t.toString());
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    //点击完成任务校验
    private void checkoutTask(final String orderId) {
        showLoadingDialog();

        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "点击完成任务校验");
        eventMap.put("comment", "点击完成任务校验");
        eventMap.put("order", orderId);

        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/staff-task/checkout", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.checkoutTask(((MyApplication) getApplication()).getRequestFieldMap(), orderId)
                        .enqueue(new Callback<CarCheckoutTaskBean>() {
                            @Override
                            public void onResponse(Call<CarCheckoutTaskBean> call, Response<CarCheckoutTaskBean> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    dismissLoadingDialog();
                                    if (response.body().getErrCode() == 0) {
                                        if (response.body().getAttachment() != null) {
                                            IntentUtil.toCarTaskActivity(mContext, orderId, carId, taskType, licenseTag, response.body().getAttachment().getIsOperate(), response.body().getAttachment().getLocationName());
                                        }
                                    } else if (response.body().getErrCode() == 11) {
                                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                        IntentUtil.toLoginActivity(mContext);
                                        AppManager.getAppManager().finishAllActivity();
                                    } else if (response.body().getErrCode() == 1001) {
                                        showOneButtonDialog("nopermission", "提醒", response.body().getMessage(), "确定");
                                    } else {
                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();

                                    }
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<CarCheckoutTaskBean> call, Throwable t) {
                                dismissLoadingDialog();
                                Log.i("neterror", "完成任务校验" + t.toString());
                                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }

    //寻车开门记录
    private void openRecord(final String orderId, final String bleCon) {
        showLoadingDialog();

        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "开门记录接口");
        eventMap.put("comment", "开门记录接口");
        eventMap.put("order", orderId);

        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/stafforder/new/openRecord", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.openRecord(((MyApplication) getApplication()).getRequestFieldMap(), orderId, bleCon)
                        .enqueue(new Callback<ResultBean>() {
                            @Override
                            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    dismissLoadingDialog();
                                    if (response.body().getErrCode() == 0) {
                                        isClickxiayibu = false;
                                        intent = new Intent(mContext, CarCheckStateActivity.class);
                                        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                        intent.putExtra(IntentKey.INTENT_CAR_ID, carId);
                                        intent.putExtra(IntentKey.INTENT_TASKTYPE, taskType);
                                        intent.putExtra(IntentKey.INTENT_LICENSETAG, licenseTag);
                                        startActivityForResult(intent, Constants.REQUEST_CAR_STATE);
                                        handler.removeCallbacks(runnable);
                                    } else if (response.body().getErrCode() == 11) {
                                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                        IntentUtil.toLoginActivity(mContext);
                                        AppManager.getAppManager().finishAllActivity();
                                    } else {
                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();

                                    }
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                dismissLoadingDialog();
                                Log.i("neterror", "寻车开门记录" + t.toString());
                                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }


    private void isOpenCheck(String isOpenCheck) {
        if (attachmentBean != null) {
            getReceiveOrderListCount();
            if ("0".equals(isOpenCheck)) {
                loadFindLayoutAndData(attachmentBean);
            } else {
                loadDrivingLayoutAndData(attachmentBean);
            }
        }

    }

    //提示打开定位服务
    private void initLocationService() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断定位服务是否开启，如果没有则开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            final DialogTwoButton inCarDialog = new DialogTwoButton(this);
            inCarDialog.setMessage(getString(R.string.LocationServiceRemind));
            inCarDialog.setYesOnclickListener("去设置", new DialogTwoButton.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                    inCarDialog.dismiss();
                }
            });
            inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    inCarDialog.dismiss();
                }
            });
            inCarDialog.setCanceledOnTouchOutside(true);
            inCarDialog.setCancelable(true);
            inCarDialog.show();
        }
    }

    public void startLocation() {
        Logger.i("bleinfor", "start");
        if (null != mLocClient) {
            mLocClient.start();
        }

    }

    private void getPermission() {
        //获取动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUEST_CODE);
            } else {
                startLocation();
            }
        } else {
            startLocation();
        }
    }

    //处理权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                new AlertDialog.Builder(mContext).setTitle("大道地服提示").setMessage("您拒绝了定位权限，无法查看工单，请您到设置中开启权限。")
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startAppSettings(mContext);
                            }
                        }).setCancelable(false).show();
            }
        }
    }

    //启动当前应用设置页面
    private static void startAppSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }


    /**
     * @param view
     * @param isAppear 弹出或隐藏
     */
    private void popCarLayout(View view, boolean isAppear, @Nullable LatLng carPosition) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        layoutHeight = DensityUtils.px2dp(mContext, view.getMeasuredHeight());
        if (Build.VERSION.SDK_INT == 19) {
            layoutHeight += DensityUtils.dp2px(mContext, 15);
        }
        if (view == layout_car_detail) {
            if (isAppear) {
                showType = 1;
                mapStatusUtils.animateMove(carPosition, 17, 300, (int) layoutHeight - 120);
                setAnimator(view, layoutHeight, 0f, 500L, true);
                setAnimator(imageView_center, 0f, -(layoutHeight - 35), 500L, true);//start：此值越小，距离越大
                setAnimator(linear_two, 0f, -(layoutHeight - 35), 500L, true);
            } else {
                showType = 0;
                setAnimator(linear_two, -(layoutHeight - 35), 0f, 500L, false);
                setAnimator(imageView_center, -(layoutHeight - 35), 0f, 500L, false);
                setAnimator(view, 0f, layoutHeight, 500L, false);
            }
        } else if (view == layout_car_find) {
            if (isAppear) {
                showType = 2;
                mapStatusUtils.animateMove(carPosition, 17, 300, (int) layoutHeight - 120);
                setAnimator(view, layoutHeight, 0f, 500L, true);
                setAnimator(linear_two, 0f, -(layoutHeight - 35), 500L, true);//start：此值越小，距离越大
                setAnimator(imageView_center, 0f, -(layoutHeight - 30), 500L, true);
            } else {
                showType = 0;
                setAnimator(linear_two, -(layoutHeight - 35), 0f, 500L, false);
                setAnimator(imageView_center, -(layoutHeight - 35), 0f, 500L, false);
                setAnimator(view, 0f, layoutHeight, 500L, false);
            }
        } else {
            if (isAppear) {
                showType = 3;
                mapStatusUtils.animateMove(carPosition, 17, 300, (int) layoutHeight - 120);
                setAnimator(view, layoutHeight, 0f, 500L, true);
                setAnimator(linear_two, 0f, -(layoutHeight - 35), 500L, true);//start：此值越小，距离越大
                setAnimator(imageView_center, 0f, -(layoutHeight - 35), 500L, true);
            } else {
                showType = 0;
                mapStatusUtils.animateMove(carPosition, 17, 300, (int) layoutHeight - 120);
                setAnimator(linear_two, -(layoutHeight - 35), 0f, 500L, false);
                setAnimator(imageView_center, -(layoutHeight - 35), 0f, 500L, false);
                setAnimator(view, 0f, layoutHeight, 500L, false);
            }
        }

    }

    private void setAnimator(final View view, final float start, float end, long duration, boolean showOrHide) {
        ObjectAnimator animator;
        animator = ObjectAnimator.ofFloat(view, "translationY", DensityUtils.dp2px(mContext, start), DensityUtils.dp2px(mContext, end));
        animator.setDuration(duration);
        if (showOrHide) {
            view.setVisibility(View.VISIBLE);
            if (view == layout_car_detail) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                        layout_car_find.setVisibility(View.GONE);
                        layout_car_driving.setVisibility(View.GONE);
                        findCarFee.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
            } else if (view == layout_car_find) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                        layout_car_detail.setVisibility(View.GONE);//展示车布局
                        layout_car_driving.setVisibility(View.GONE);//行驶中布局
                        findCarFee.setVisibility(View.GONE);//停车费布局
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                        layout_car_receivedorder.setVisibility(View.VISIBLE);
                        layout_search.setVisibility(View.GONE);
                        imageView_refresh.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });

            } else if (view == layout_car_driving) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                        layout_car_detail.setVisibility(View.GONE);
                        layout_car_find.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                        //动画结束后，显示停车费提示
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) findCarFee.getLayoutParams();
                        params.setMargins(0, 0, 0, DensityUtils.dp2px(mContext, start + 10));
                        findCarFee.setLayoutParams(params);
                        findCarFee.setVisibility(View.VISIBLE);
                        layout_search.setVisibility(View.GONE);
                        layout_car_receivedorder.setVisibility(View.VISIBLE);
                        imageView_refresh.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
            }
        } else {
            if (view == layout_car_detail || view == layout_car_find || view == layout_car_driving) {
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        isAnimatorShow = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        isAnimatorShow = false;
                        layout_car_detail.setVisibility(View.GONE);
                        layout_car_find.setVisibility(View.GONE);
                        layout_car_driving.setVisibility(View.GONE);
                        findCarFee.setVisibility(View.GONE);
                        layout_car_receivedorder.setVisibility(View.GONE);
                        layout_search.setVisibility(View.VISIBLE);
                        imageView_refresh.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
            }

        }
        animator.start();
    }


    private void loadOrderDetailLayout(List<CarOrderBean.AttachmentBean> listCarOrder, final String reciveType) {
        if (listCarOrder != null && listCarOrder.size() > 0) {
            if (listCarOrder.size() == 1) {
                vpCar.canLoop(false);
                orderIndex = 0;
            } else {
                vpCar.canLoop(true);
                orderIndex = 1;
            }
            carsPagerAdapter = new CarsPagerAdapter(mContext, listCarOrder);
            vpCar.setAdapter(carsPagerAdapter);

            attachmentBean = listCarOrder.get(0);
            orderId = attachmentBean.getOrderId();
            carId = attachmentBean.getCarId();
            taskType = attachmentBean.getTaskType();
            licenseTag = attachmentBean.getLicenseTag();
            foundCarPosition = new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude());
            popCarLayout(layout_car_detail, true, foundCarPosition);
            iv_getorder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM) != null) {
                        receiveOrder(orderId, licenseTag, reciveType, orderIndex);
                    } else {
                        startActivity(new Intent(mContext, LoginNewActivity.class));
                    }
                }
            });
            //获取还车备注
            getReturnComment(attachmentBean.getDistributeReason(), attachmentBean.getIsAccurate(), attachmentBean.getCarId(), attachmentBean.getRemark(), 1, foundCarPosition);
        }
    }

    //接单中
    private void loadFindLayoutAndData(final CarOrderBean.AttachmentBean attachmentBean) {
        //车辆在线 可以有用户预约
        handler.post(runnable);//轮询车状态
        mBaiduMap.clear();
        BluetoothHelper.getInstance().removeBleInfo(mContext);//start
        BluetoothHelper.getInstance().stopScanDevice();
        BluetoothHelper.getInstance().disConnectDevice();
        if (attachmentBean != null) {
            this.attachmentBean = attachmentBean;
            orderId = attachmentBean.getOrderId();
            carId = attachmentBean.getCarId();
            taskType = attachmentBean.getTaskType();
            licenseTag = attachmentBean.getLicenseTag();
            Logger.i("distance", attachmentBean.getLatitude() + "   " + attachmentBean.getLongitude());
            foundCarPosition = new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude());
            getDriveTracks();//鹰眼轨迹展示
            popCarLayout(layout_car_find, true, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()));
            tv_order_license.setText(licenseTag);
            Glide.with(mContext).load(MyApplication.imageUrl + attachmentBean.getCarImg()).into(iv_car);
            BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);//获取蓝牙信息
            //寻车距离
            if (foundCarPosition != null) {
                Logger.i("distance", DistanceUtil.getDistance(curPosition, foundCarPosition) + "=====" + SPUtils.getInstance(mContext).getIntValue(SPKey.FIND_CAR_DISTANCE));
                if (DistanceUtil.getDistance(curPosition, foundCarPosition)
                        <= SPUtils.getInstance(mContext).getIntValue(SPKey.FIND_CAR_DISTANCE)) {
                    car_find.setVisibility(View.VISIBLE);
                } else {
                    car_find.setVisibility(View.INVISIBLE);
                }
            }
            // 路线 和导航监听
            RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_WALK, curPosition, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()), null);
            markerUtils.showEndPositionIcon(mBaiduMap, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()), 0, R.drawable.park_marker);
            getReturnComment(attachmentBean.getDistributeReason(), attachmentBean.getIsAccurate(), attachmentBean.getCarId(), attachmentBean.getRemark(), 2, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()));
            //获取最后使用者定位
            getlastUserLocation(carId);
        }
    }

    private void getlastUserLocation(String carId) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getlastUserLocation(MyApplication.getInstance().getRequestFieldMap(), carId).enqueue(new Callback<lastUserLocation>() {
            @Override
            public void onResponse(Call<lastUserLocation> call, Response<lastUserLocation> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0 && response.body().getAttachment() != null) {
                        lastUserPhoneLocation = new LatLng(response.body().getAttachment().getLatitude()
                                , response.body().getAttachment().getLongitude());
                        markerUtils.addLastUserPhoneMarkerToMap(lastUserPhoneLocation);
                    }
                }
            }

            @Override
            public void onFailure(Call<lastUserLocation> call, Throwable t) {

            }
        });
    }

    //行驶中
    private void loadDrivingLayoutAndData(final CarOrderBean.AttachmentBean attachmentBean) {
        handler.removeCallbacks(runnable);//移除轮询
        mBaiduMap.clear();

        if (attachmentBean != null) {
            this.attachmentBean = attachmentBean;
            orderId = attachmentBean.getOrderId();
            carId = attachmentBean.getCarId();
            taskType = attachmentBean.getTaskType();
            licenseTag = attachmentBean.getLicenseTag();
            foundCarPosition = new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude());
        }
        tv_inUse_license.setText(licenseTag);
        popCarLayout(layout_car_driving, true, new LatLng(attachmentBean.getLatitude(), attachmentBean.getLongitude()));
        //获取蓝牙信息
        getBleInfoAndSearch();
        //0:调度 1:充电 2:什么都不做 不可运营时不匹配终点 3：加油
        if (actionBean != null) {
            if (!TextUtils.isEmpty(actionBean.getPreditScore())) {
                linear_jifen.setVisibility(View.VISIBLE);
                tv_jifen.setText(actionBean.getPreditScore());
            } else {
                linear_jifen.setVisibility(View.GONE);
            }

            if ("0".equals(actionBean.getActionType())) {
                searchCarOrderByRange(actionBean.getLatitude() + "", actionBean.getLongitude() + "", orderId, "");
                //调度附带洗车工单
                if ("yes".equals(actionBean.getIsWashCar())) {
                    RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, new LatLng(actionBean.getWashLatitude(), actionBean.getWashLongitude()), new LatLng(actionBean
                            .getLatitude(), actionBean.getLongitude()), null);
                    markerUtils.showWashCarIcon(mBaiduMap, new LatLng(actionBean.getWashLatitude(), actionBean.getWashLongitude()), R.drawable.washcar_mark);
                } else {
                    RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, curPosition, new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), null);
                }
                markerUtils.showEndPositionIcon(mBaiduMap, new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), actionBean.getOperateRange(), R.drawable.icon_baiduendposition);
                markerUtils.showFindCarInfoWindow(actionBean.getLocation(), new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), new MarkerUtils.NaviButtonClickListener() {
                    @Override
                    public void onClick() {
                        showNaviDialog(new LatLng(actionBean.getLatitude(), actionBean.getLongitude()));
                    }
                });
            } else if ("1".equals(actionBean.getActionType())) {
                queryStation(attachmentBean.getLatitude() + "", attachmentBean.getLongitude() + "", "1");
            } else if ("2".equals(actionBean.getActionType())) {
                searchCarOrderByRange(attachmentBean.getLatitude() + "", attachmentBean.getLongitude() + "", orderId, "");
            } else if ("3".equals(actionBean.getActionType())) {
                //加油工单
                markerUtils.showEndPositionIcon(mBaiduMap, new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), actionBean.getOperateRange(), R.drawable.icon_baiduendposition);
                RoutePlan.getInstance().startRoutePlan(mBaiduMap, RoutePlan.PLAN_DRIVE, curPosition, new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), null);
                markerUtils.showFindCarInfoWindow(actionBean.getLocation(), new LatLng(actionBean.getLatitude(), actionBean.getLongitude()), new MarkerUtils.NaviButtonClickListener() {
                    @Override
                    public void onClick() {
                        showNaviDialog(new LatLng(actionBean.getLatitude(), actionBean.getLongitude()));
                    }
                });
                //加油站
                searchCarOrderByRange(actionBean.getLatitude() + "", actionBean.getLongitude() + "", orderId, "");
                queryStation(attachmentBean.getLatitude() + "", attachmentBean.getLongitude() + "", "2");
            }
        }
        //还车备注评价
        getCommentHelpful(attachmentBean.getCarId());
    }

    //导航dialog
    private void showNaviDialog(final LatLng carPosition) {
        final ChooseNaviDialog chooseNaviDialog = new ChooseNaviDialog(mContext);
        chooseNaviDialog.setOnItemClickListener(new ChooseNaviDialog.OnItemClickListener() {
            @Override
            public void onClickItem(int position) {
                if (position == 0) {
                    try {
                        // 构建 route搜索参数以及策略，起终点也可以用name构造
                        RouteParaOption para = new RouteParaOption()
                                .startPoint(curPosition)
                                .endPoint(carPosition);
                        BaiduMapRoutePlan.openBaiduMapWalkingRoute(para, mContext);
                    } catch (Exception e) {
                        ToastUtils.makeText(mContext, "启动百度地图失败", ToastUtils.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                } else {
                    if (SDCardUtils.checkApkExist(mContext, "com.autonavi.minimap")) {
                        try {
                            LatLng gaoDeCurPosition = BaiduMapParams.gaoDeToBaidu(curPosition);
                            LatLng gaoDeCarPosition = BaiduMapParams.gaoDeToBaidu(carPosition);
                            intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.setPackage("com.autonavi.minimap");
                            intent.setData(Uri.parse("androidamap://route/plan/?sourceApplication=大道工单系统&slat=" + gaoDeCurPosition.latitude + "&slon=" + gaoDeCurPosition.longitude + "&dlat=" + gaoDeCarPosition.latitude + "&dlon=" + gaoDeCarPosition.longitude + "&dev=0&t=2"));
                            startActivity(intent);
                        } catch (Exception e) {
                            ToastUtils.makeText(mContext, "启动高德地图失败", ToastUtils.LENGTH_SHORT).show();
                        }
                    } else {
                        ToastUtils.makeText(mContext, "未安装高德地图", ToastUtils.LENGTH_SHORT).show();
                    }
                }
                chooseNaviDialog.dismiss();
            }
        });
        chooseNaviDialog.show();
    }

    private void showUnFinishDialog(final CarOrderBean.AttachmentBean attachmentBean) {
        unFinishTravelDialog.setMessage(getString(R.string.haveOrder));
        unFinishTravelDialog.setYesOnclickListener("进入", new DialogOneButton.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                isOpenCheck(attachmentBean.getIsOpenCheck());
                unFinishTravelDialog.dismiss();
            }
        });
        unFinishTravelDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    backPress(true);
                    return true;
                }
                return false;
            }

        });
        unFinishTravelDialog.setCanceledOnTouchOutside(true);
        unFinishTravelDialog.setCancelable(true);
        if (!unFinishTravelDialog.isShowing()) {
            unFinishTravelDialog.show();
        }
    }

    //对话框
    private void showOneButtonDialog(final String flag, String title, String message, String yestext) {
        final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
        dialogOneButton.setTitle(title);
        dialogOneButton.setMessage(message);
        dialogOneButton.setCancelable(false);
        dialogOneButton.setCanceledOnTouchOutside(false);
        dialogOneButton.setYesOnclickListener(yestext, new DialogOneButton.onYesOnclickListener() {
            @Override
            public void onYesClick() {

                if ("checkCarStatus".equals(flag)) {

                } else if ("locationException".equals(flag)) {
                    AppManager.getAppManager().AppExit(mContext);

                } else if ("permission".equals(flag)) {
                    intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                } else if ("locationfail".equals(flag)) {
                    intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                } else if ("unfinishtask".equals(flag)) {

                } else if ("nopermission".equals(flag)) {

                }
                dialogOneButton.dismiss();
            }
        });
        dialogOneButton.show();

    }

    //接多单对话框
    private void showDialogReceiveMore(CarOrderBean.AttachmentBean attachmentBean) {
        final DialogOrderDetail dialogReceiveMore = new DialogOrderDetail(mContext);
        dialogReceiveMore.setDetail(attachmentBean);
        dialogReceiveMore.setYesOnclickListener(new DialogOrderDetail.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                if (SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM) != null) {
                    receiveOrder(attachmentBean.getOrderId(), attachmentBean.getLicenseTag(), "4", 0);
                } else {
                    startActivity(new Intent(mContext, LoginNewActivity.class));
                }
                dialogReceiveMore.dismiss();
            }
        });
        dialogReceiveMore.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (callParse != null) {
                    callParse.cancel();
                }
                compositeDisposable.clear();
                mBaiduMap.hideInfoWindow();
                if (actionBean != null && ("0".equals(actionBean.getActionType()) || "2".equals(actionBean.getActionType()) || "3".equals(actionBean.getActionType()))) {
                    searchCarOrderByRange(attachmentBean.getLatitude() + "", attachmentBean.getLongitude() + "", orderId, "");
                }

            }
        });
        dialogReceiveMore.show();

    }

    //寻车倒计时
    private void findCarTimer(final long placeOrderTimer) {
        timer = new CountDownTimer(placeOrderTimer + 1000, 1000) {
            @Override
            public void onTick(long l) {//15min
                tx_reserve_order_timer.setText(TimeUtils.formatSecondCount(l / 1000 + "", 2));
                countDownIndicate.setProgress((int) ((double) l / 1000 / 60 / 15 * 100));
            }

            @Override
            public void onFinish() {
                //重新检测任务状态
            }
        };
        timer.start();
        acquireWakeLock();
    }

    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }

    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    @Override
    public void onBackPressed() {
        backPress(true);
    }

    private void backPress(boolean isExit) {
        if (!isAnimatorShow && showType == 1) {
            mBaiduMap.hideInfoWindow();
            popCarLayout(layout_car_detail, false, null);
        } else if (isExit) {
            exit();
        }
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再按一次退出大道工单系统", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            AppManager.getAppManager().AppExit(mContext);
            BluetoothHelper.getInstance().unregisterBluetoothStateListener();
        }
    }

    private void showCancelTask() {
        final DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
        dialogTwoButton.setTitle("提醒");
        dialogTwoButton.setMessage("确定取消任务吗");
        dialogTwoButton.setYesOnclickListener("暂不", new DialogTwoButton.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                dialogTwoButton.dismiss();
            }
        });
        dialogTwoButton.setNoOnclickListener("确定", new DialogTwoButton.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                cancelTask(orderId);
                dialogTwoButton.dismiss();
            }
        });
        dialogTwoButton.show();
    }


    @Override
    protected void onResume() {
        Logger.i("bleinfor", "onResume====" + "carId==" + carId);
        useCar.setVisibility(View.VISIBLE);
        mapView.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        //蓝牙状态监听
        if (showType == 3) {
            BluetoothHelper.getInstance().registerBluetoothStateListener(new BluetoothStateListener() {
                @Override
                public void onBluetoothStateChanged(boolean openOrClosed) {
                    Logger.i("bleinfo", "openOrClosed=" + openOrClosed);
                    operateType = null;
                    if (openOrClosed) {//开
                        if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                            showLoadingDialog();
                            BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
                        }
                    } else {
                        tv_blueState.setText("蓝牙未匹配");
                        BluetoothHelper.getInstance().openBluetooth(CarNewMainMapActivity.this, 100);
                    }
                }
            });
        }
        //注册网络状态监听
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onComplete(CompleteBean completeBean) {
        popCarLayout(layout_car_driving, false, curPosition);
        mBaiduMap.clear();
        getunfinishOrder();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onForeground(ForegroundBean foregroundBean) {
        getSpecialOrderList();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Logger.i("bleinfor", "onNewIntent" + "carId==" + carId);
        if (intent.getIntExtra("intentFrom", 0) == 1) {//从完成任务进入首页
            popCarLayout(layout_car_driving, false, curPosition);
            mBaiduMap.clear();
            getunfinishOrder();
        } else if (intent.getIntExtra("intentFrom", 0) == 2) {//从登录界面进入首页
            popCarLayout(layout_car_detail, false, curPosition);
            popCarLayout(layout_car_find, false, curPosition);
            popCarLayout(layout_car_driving, false, curPosition);
            initApp();
        }
        super.onNewIntent(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode != RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
                dismissLoadingDialog();
                tv_blueState.setText("蓝牙未匹配");
            } else if (resultCode == RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
                Logger.i("bleinfo", "open" + "开始扫描");
                showLoadingDialog();
                BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
            } else if (requestCode == Constants.REQUEST_LOCATION_SERVICE) {//开启定位服务返回结果
                isFirstLocationError = true;
                initLocationService();
            } else if (requestCode == Constants.REQUEST_CAR_STATE && resultCode == Constants.REQUEST_CAR_STATE) {
                actionBean = (StaffOrderBean.AttachmentBean.ActionBean) data.getSerializableExtra("actionBean");
                isOpenCheck("1");
            } else if (requestCode == Constants.REQUEST_CAR_RECEIVEDLIST && resultCode == Constants.REQUEST_CAR_RECEIVEDLIST) {
                CarTaskStateBean.AttachmentBean unfinishAttachment = (CarTaskStateBean.AttachmentBean) data.getSerializableExtra("orderBean");
                actionBean = (StaffOrderBean.AttachmentBean.ActionBean) data.getSerializableExtra("actionBean");
                attachmentBean = unfinishAttachment.getStaffCarOrderModel();
                isOpenCheck(attachmentBean.getIsOpenCheck());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 锁车 开车的请求接口
    private void controlCar(final String command, String action, String comment) {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", action);
        eventMap.put("comment", comment);
        eventMap.put("car", licenseTag);
        eventMap.put("order", orderId);
        eventMap.put("command", command);

        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/car/control", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.controlCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, command, businessType)
                        .enqueue(new Callback<ResultBean>() {
                            @Override
                            public void onResponse(Call<ResultBean> call, final Response<ResultBean> response) {
                                try {
                                    if (response.isSuccessful() && response.body() != null) {
                                        dismissLoadingDialog();
                                        if (response.body().getErrCode() == 0) {
                                            ToastUtils.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                        } else if (response.body().getErrCode() == 11) {
                                            intent = new Intent(mContext, LoginNewActivity.class);
                                            startActivity(intent);
                                            AppManager.getAppManager().finishAllActivity();
                                        } else {
                                            ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                                        }
                                    } else {
                                        dismissLoadingDialog();
                                        ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();

                            }
                        });
            }
        });
    }

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    private void getReturnComment(int distributeReason, int isAc, String carId, String remark, int showType, final LatLng markerPosition) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getReturnCarComment("epimetheus/v1/rcc/" + carId)
                .retry(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReturnCarCommentBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(ReturnCarCommentBean returnCarCommentBean) {
                        if (returnCarCommentBean.getMsg_code() == 200) {
                            Logger.d("returncommnet", "获取了还车备注");
                            String userRemark = returnCarCommentBean.getAttachment().getComment().getRemarkMsg();
                            String remarkPic = "";
                            if (!TextUtils.isEmpty(returnCarCommentBean.getAttachment().getComment().getImgs())) {
                                remarkPic = returnCarCommentBean.getAttachment().getComment().getImgs().replace(",,", ",");
                            }
                            if (showType == 1) {//车详情
                                Logger.d("getRemarkMsg1" + userRemark + "     " + "imgs" + remarkPic);
                                markerUtils.showCarLocationInfoWindow(distributeReason, userRemark, remark, remarkPic, markerPosition, isAc);
                            } else {//寻车中
                                Logger.d("getRemarkMsg2" + userRemark + "     " + "imgs" + remarkPic);
                                markerUtils.showFindCarInfoAndRemarkWindow(userRemark, remark, remarkPic, markerPosition, isAc, new MarkerUtils.NaviButtonClickListener() {
                                    @Override
                                    public void onClick() {
                                        showNaviDialog(markerPosition);
                                    }
                                });
                            }
                        } else {
                            Logger.d("returncommnet", "获取还车备注错误");
                            String remarkPic = "";
                            GeoCoderUtils.getInstance().reverseGeoCode(markerPosition, new GeoCoderUtils.OnGeoListener() {
                                @Override
                                public void onGeoSuccess(String address, String cityCode, String city, String adcode) {
                                    String userRemark = address;
                                    Logger.d("returncommnet", "地理编码成功" + address);
                                    if (showType == 1) {//车详情
                                        Logger.d("getRemarkMsg1" + userRemark + "     " + "imgs" + remarkPic);
                                        markerUtils.showCarLocationInfoWindow(distributeReason, userRemark, remark, remarkPic, markerPosition, isAc);
                                    } else {//寻车中
                                        Logger.d("getRemarkMsg2" + userRemark + "     " + "imgs" + remarkPic);
                                        markerUtils.showFindCarInfoAndRemarkWindow(userRemark, remark, remarkPic, markerPosition, isAc, new MarkerUtils.NaviButtonClickListener() {
                                            @Override
                                            public void onClick() {
                                                showNaviDialog(markerPosition);
                                            }
                                        });
                                    }
                                }

                                @Override
                                public void onGeoFailure() {
                                    Logger.d("returncommnet", "地理编码失败");
                                    String userRemark = "";
                                    if (showType == 1) {//车详情
                                        Logger.d("getRemarkMsg1" + userRemark + "     " + "imgs" + remarkPic);
                                        markerUtils.showCarLocationInfoWindow(distributeReason, userRemark, remark, remarkPic, markerPosition, isAc);
                                    } else {//寻车中
                                        Logger.d("getRemarkMsg2" + userRemark + "     " + "imgs" + remarkPic);
                                        markerUtils.showFindCarInfoAndRemarkWindow(userRemark, remark, remarkPic, markerPosition, isAc, new MarkerUtils.NaviButtonClickListener() {
                                            @Override
                                            public void onClick() {
                                                showNaviDialog(markerPosition);
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    //备注评价
    private void getCommentHelpful(String carId) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getReturnCarComment("epimetheus/v1/rcc/" + carId)
                .retry(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReturnCarCommentBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(ReturnCarCommentBean returnCarCommentBean) {
                        if (returnCarCommentBean.getMsg_code() == 200) {
                            Logger.d("comment_main", "获取了还车备注");
                            if ((returnCarCommentBean.getAttachment().getStaff_remark() != null && !returnCarCommentBean.getAttachment().getStaff_remark().getStaff_id().equals(orderId)) || returnCarCommentBean.getAttachment().getStaff_remark() == null) {
                                List<String> piclist = new ArrayList<>();
                                if (!TextUtils.isEmpty(returnCarCommentBean.getAttachment().getComment().getImgs())) {
                                    piclist = Arrays.asList(returnCarCommentBean.getAttachment().getComment().getImgs().replace(",,", ",").split(","));
                                }
                                String comment_id = returnCarCommentBean.getAttachment().getId();
                                DialogCommentButton dialogCommentButton = new DialogCommentButton(mContext, piclist);
                                dialogCommentButton.setMessage("备注地址:" + returnCarCommentBean.getAttachment().getComment().getRemarkMsg() + "");
                                dialogCommentButton.setCancelable(false);
                                dialogCommentButton.setCanceledOnTouchOutside(false);
                                dialogCommentButton.setYesOnclickListener("非恶意", new DialogCommentButton.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        dialogCommentButton.dismiss();
                                        commitCommentEvaluate(comment_id, 1);
                                    }
                                });
                                dialogCommentButton.setNoOnclickListener("恶意描述", new DialogCommentButton.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        dialogCommentButton.dismiss();
                                        commitCommentEvaluate(comment_id, 2);
                                    }
                                });
                                dialogCommentButton.setPicOnclickListener(new DialogCommentButton.onPictureClickListener() {
                                    @Override
                                    public void onPictureClick() {
                                        Intent intent = new Intent(mContext, PhotoViewActivity.class);
                                        intent.putStringArrayListExtra("pictures", new ArrayList<>(Arrays.asList(returnCarCommentBean.getAttachment().getComment().getImgs().replace(",,", ",").split(","))));
                                        int location[] = new int[2];
                                        dialogCommentButton.ivComment.getLocationOnScreen(location);
                                        intent.putExtra("left", location[0]);
                                        intent.putExtra("top", location[1]);
                                        intent.putExtra("height", dialogCommentButton.ivComment.getHeight());
                                        intent.putExtra("width", dialogCommentButton.ivComment.getWidth());
                                        mContext.startActivity(intent);
                                    }
                                });
                                dialogCommentButton.show();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void commitCommentEvaluate(String comment_id, int isHelpful) {
        showLoadingDialog();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            jsonObject.put("staff_id", orderId);
            jsonObject.put("is_helpful", isHelpful);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).commitCommentEvaluate("epimetheus/v1/comments/" + comment_id + "/remark", requestBody).enqueue(new Callback<ReturnCarCommentBean>() {
            @Override
            public void onResponse(Call<ReturnCarCommentBean> call, Response<ReturnCarCommentBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200) {
                    ToastUtils.makeText(mContext, "提交成功", ToastUtils.LENGTH_SHORT);
                }
            }

            @Override
            public void onFailure(Call<ReturnCarCommentBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onPause() {
        Logger.i("bleinfor", "onPause");
        //未允许定位权限，地图不执行onPause;这是为了解决：进入首页，弹出申请定位权限对话框，首页onPause,此时地图还未渲染完导致页面黑屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mapView.onPause();
            }
        } else {
            mapView.onPause();
        }
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        //解注册网络状态监听
        unregisterReceiver(netWorkStateReceiver);
        super.onPause();
    }

    @Override
    protected void onStop() {
        Logger.i("bleinfor", "onStop");
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        BluetoothHelper.getInstance().unregisterBluetoothStateListener();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        MapView.setMapCustomEnable(false);
        mapView.onDestroy();
        mapView = null;
        BaiduMapRoutePlan.finish(this);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    BluetoothHelper.BothSearchResponse bothSearchResponse = new BluetoothHelper.BothSearchResponse() {
        @Override
        public void onSearchSuccess(String mac, String bleName) {
            Logger.i("bleinfo", "onSearchSuccess");
            BluetoothHelper.getInstance().connectDevice(connectResponse, 1);
        }

        @Override
        public void onSearchTimeout() {
            dismissLoadingDialog();
            Logger.i("bleinfo", "扫描超时");
            ApiStore.bleRecord("2", orderId, carId, "connect");
            if (showType == 2 && isClickxiayibu) {
                openRecord(orderId, "2");
            } else if (showType == 3) {
                if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                    controlCar("close", "行驶中关门", "行驶中关门");
                } else if (operateType == BleConstants.OperateType.OPEN_DOOR_POWER) {
                    controlCar("open", "行驶中开门", "行驶中开门");
                }
            }
        }

        @Override
        public void onSearchTimeoutEveryTime() {

        }
    };

    /**
     * 蓝牙连接的结果
     */
    BluetoothHelper.BothConnectResponse connectResponse = new BluetoothHelper.BothConnectResponse() {
        @Override
        public void onConnectSuccess() {
            dismissLoadingDialog();
            Logger.i("bleinfo", "连接上了");
            ApiStore.bleRecord("1", orderId, carId, "connect");
            if (showType == 2 && isClickxiayibu) {
                openRecord(orderId, "1");
            } else if (showType == 3) {
                tv_blueState.setText("蓝牙已匹配");
            }
        }

        @Override
        public void onConnectFailed(String error) {
            dismissLoadingDialog();
            Logger.i("bleinfo", "连接失败,寻车/行驶中");
            ApiStore.bleRecord("2", orderId, carId, "connect");
            if (showType == 2 && isClickxiayibu) {
                openRecord(orderId, "2");
            } else if (showType == 3) {
                tv_blueState.setText("蓝牙未匹配");
                if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                    controlCar("close", "行驶中关门", "行驶中关门");
                } else if (operateType == BleConstants.OperateType.OPEN_DOOR_POWER) {
                    controlCar("open", "行驶中开门", "行驶中开门");
                }
            }
        }

        @Override
        public void onConnectTimeoutEveryTime() {

        }
    };
    BluetoothHelper.OnOperateCarListener onOperateCarListener = new BluetoothHelper.OnOperateCarListener() {

        @Override
        public void onOperateSuccess(int[] status) {
            dismissLoadingDialog();
            if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                ToastUtils.makeText(mContext, "关门成功", ToastUtils.LENGTH_SHORT).show();
                ApiStore.bleRecord("1", orderId, carId, "closePowerDown");
            } else if (operateType == BleConstants.OperateType.OPEN_DOOR_POWER) {
                ToastUtils.makeText(mContext, "开门成功", ToastUtils.LENGTH_SHORT).show();
                ApiStore.bleRecord("1", orderId, carId, "openPowerOn");
            } else {
                ToastUtils.makeText(mContext, "操作成功", ToastUtils.LENGTH_SHORT).show();
            }
            if (showType == 2 && isClickxiayibu) {
                openRecord(orderId, "1");
            }
        }

        @Override
        public void onOperateFailure(String error) {
            dismissLoadingDialog();
            if (operateType == BleConstants.OperateType.CLOSE_DOOR_POWER) {
                controlCar("close", "行驶中关门", "行驶中关门");
                ApiStore.bleRecord("2", orderId, carId, "closePowerDown");
            } else if (operateType == BleConstants.OperateType.OPEN_DOOR_POWER) {
                controlCar("open", "行驶中开门", "行驶中开门");
                ApiStore.bleRecord("2", orderId, carId, "openPowerOn");
            }
            if (showType == 2 && isClickxiayibu) {
                openRecord(orderId, "1");
            }
        }
    };

}
